<!-- 跟进记录 -->
<template>
    <ArtTableFullScreen>
      <div class="account-page" id="table-full-screen">
        <!-- 搜索栏 -->
        <ArtSearchBar
          v-model:filter="formFilters"
          :items="formItems"
          :showExpand="false"
          @reset="handleReset"
          @search="handleSearch"
        ></ArtSearchBar>
  
        <ElCard shadow="never" class="art-table-card">
          <!-- 表格头部 -->
          <ArtTableHeader
            :columnList="columnOptions"
            v-model:columns="columnChecks"
            @refresh="handleRefresh"
          >
            <template #left>
              <ElButton @click="showDialog('add')">新增</ElButton>
            </template>
          </ArtTableHeader>
  
          <!-- 表格 -->
          <ArtTable
            ref="tableRef"
            row-key="id"
            :loading="loading"
            :data="tableData"
            :currentPage="1"
            :pageSize="20"
            :total="500"
            :marginTop="10"
            :pagination="true"
            @selection-change="handleSelectionChange"
          >
            <template #default>
              <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
            </template>
          </ArtTable>
          <EditForm
            v-model="dialogVisible"
            :type="dialogType"
            :role-list="roleList"
            :initial-form-data="formData"
            @submit="handleDialogSubmit"
            @cancel="handleDialogCancel"
          />
        </ElCard>
      </div>
    </ArtTableFullScreen>
  </template>
  
  <script setup lang="ts">
    import { h } from 'vue'
    import { ROLE_LIST_DATA,CUSTOMER_SOURCE_LIST_DATA } from '@/views/customer/type/const'
    import { SearchChangeParams, SearchFormItem } from '@/types/search-form'
    import { ElDialog, FormInstance, ElTag } from 'element-plus'
    import { ElMessageBox, ElMessage } from 'element-plus'
    import { useCheckedColumns } from '@/composables/useCheckedColumns'
    import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
    import EditForm from './components/EditForm.vue'
    import { CustomerOpenSeaApi } from '@/api/customer/openSea'
    import { ApiStatus } from '@/utils/http/status'
    import { 
        CustomerSourceFormData, 
        CustomerSourceItem, 
        CustomerSourceListParams,
        CustomerSourceListResponse
    } from './types'
  
    const dialogType = ref('add')
    const dialogVisible = ref(false)
    const loading = ref(false)
  
    // 定义表单搜索初始值
    const initialSearchState = {
      sourceName: '',
      sourceCode: '',
      status: 1
    }

    // 表单实例
    const formRef = ref<FormInstance>()
  
    // 表单数据
    const formData = reactive<CustomerSourceFormData>({
      sourceName: '',
      sourceCode: '',
			status: 1
    })
  
    const roleList = ref<any[]>([])
  
    // 响应式表单数据
    const formFilters = reactive({ ...initialSearchState })
  
    // 表格数据
    const tableData = ref<any[]>([])
  
    // 表格实例引用
    const tableRef = ref()
  
    // 选中的行数据
    const selectedRows = ref<any[]>([])
  
    // 重置表单
    const handleReset = () => {
      Object.assign(formFilters, { ...initialSearchState })
    }
  
    // 搜索处理
    const handleSearch = () => {
      console.log('搜索参数:', formFilters)
      getTableList()
    }
  
    // 表单项变更处理
    const handleFormChange = (params: SearchChangeParams): void => {
      console.log('表单项变更:', params)
    }
  
    // 表单配置项
    const formItems: SearchFormItem[] = [
      {
        label: '类型名称',
        prop: 'sourceName',
        type: 'input',
        config: {
          clearable: true
        },
        onChange: handleFormChange
      },
  
      {
        label: '类型编码',
        prop: 'sourceCode',
        type: 'input',
        config: {
          clearable: true
        },
        onChange: handleFormChange
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        options: [
          { label: '启用', value: 1 },
          { label: '停用', value: 0 }
        ],
        onChange: handleFormChange
      }
    ]
  
    // 列配置
    const columnOptions = [
      { label: '类型名称', type: 'sourceName' },
      { label: '类型编码', type: 'sourceCode' },
      { label: '状态', type: 'status' },
      { label: '创建日期', type: 'create_time' },
      { label: '操作', type: 'operation' }
    ]
  
    // 获取标签类型
    // 1: 在线 2: 离线 3: 异常 4: 注销
    const getTagType = (status: number | string) => {
      switch (status) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case '2':
          return 'info'
        case '3':
          return 'warning'
        default:
          return 'info'
      }
    }
  
    // 构建标签文本
    const buildTagText = (status: number | string) => {
      let text = '启用'
      switch (status) {
        case 0:
					text = '停用'
        case 1:
					text = '启用'
        default:
					text = '启用'
      }
      return text
    }
  
    // 显示对话框
    const showDialog = (type: string, row?: CustomerSourceItem) => {
      dialogVisible.value = true
      dialogType.value = type
  
      // 重置表单验证状态
      if (formRef.value) {
        formRef.value.resetFields()
      }
  
      if (type === 'edit' && row) {
        Object.assign(formData, row)
      } else {
        Object.assign(formData, {
          sourceName: '',
          sourceCode: '',
          status: 1
        })
        delete formData.id // 如果 id 是可选的，在新增时删除它
      }
    }
		// 处理对话框提交
		const handleDialogSubmit = async(data: CustomerSourceFormData) => { 
				dialogVisible.value = false
				getTableList()  // 刷新列表
		}
		// 处理对话框取消
		const handleDialogCancel = () => {
			dialogVisible.value = false
		}
    // 删除用户
    const deleteUser = (data: any) => {
      ElMessageBox.confirm('确定要删除该类型吗？', '删除类型', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async() => {
        try{
          const params = {id: data.id}
          const res = await CustomerOpenSeaApi.deleteCustomerSource(params)
          if (res.code === ApiStatus.success) {
            ElMessage.success('删除成功')
          }
          dialogVisible.value = false
          getTableList()  // 刷新列表
        }catch(err){
          console.error('操作失败:', err)
          ElMessage.error('操作失败，请重试')
        }
      })
    }
  
    // 动态列配置
    const { columnChecks, columns } = useCheckedColumns(() => [
			{ prop: 'sourceName', label: '类型名称' },
			{ prop: 'sourceCode', label: '类型编码' },
      {
        prop: 'status',
        label: '状态',
        formatter: (row) => {
          return h(ElTag, { type: getTagType(row.status) }, () => buildTagText(row.status))
        }
      },
      {
        prop: 'create_time',
        label: '创建日期',
        sortable: true
      },
      {
        prop: 'operation',
        label: '操作',
        width: 150,
        // fixed: 'right', // 固定在右侧
        // disabled: true,
        formatter: (row: any) => {
          return h('div', [
            h(ArtButtonTable, {
              type: 'edit',
              onClick: () => showDialog('edit', row)
            }),
            h(ArtButtonTable, {
              type: 'delete',
              onClick: () => deleteUser(row)
            })
          ])
        }
      }
    ])
  
    onMounted(() => {
      getTableList()
      getRoleList()
    })
  
    const getTableList = async () => {
      loading.value = true
      setTimeout(() => {
        tableData.value = CUSTOMER_SOURCE_LIST_DATA
        loading.value = false
      }, 500)
			// 请求接口
			const params = {...formFilters}
      const res = await CustomerOpenSeaApi.getTableData(params)
      if (res.code === ApiStatus.success) {
        tableData.value = res.data.list
      }
    }
  
    const getRoleList = () => {
      roleList.value = ROLE_LIST_DATA
    }
  
    const handleRefresh = () => {
      getTableList()
    }
  
    // 处理表格行选择变化
    const handleSelectionChange = (selection: any[]) => {
      selectedRows.value = selection
    }
  
  </script>
  
  <style lang="scss" scoped>
    .account-page {
      :deep(.user) {
        .avatar {
          width: 40px;
          height: 40px;
          border-radius: 6px;
        }
  
        > div {
          margin-left: 10px;
  
          .user-name {
            font-weight: 500;
            color: var(--art-text-gray-800);
          }
        }
      }
    }
  </style>
  